import fs from 'fs';
import { connection } from '../app/database/mysql';
import { complaintModel } from './complaint.model';
import { APP_URL, STATIC_PATH } from '../app/app.config';

/**
 * 获取内容
 */
export const getComplaint = async () => {
  // 准备查询
  const statement = `
    SELECT * FROM complaint ORDER by id DESC
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data;
}

/**
 * 按 ID 获取内容
 */
export const getIdComplaint = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM complaint
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data[0];
}

/**
 * 创建内容
 */
export const createComplaint = async (post: complaintModel) => {
  // 准备查询
  const statement = `
    INSERT INTO complaint
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateComplaint = async (post: complaintModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE complaint
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteComplaint = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM complaint
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 存储文件信息
 */
export const createFile = async (
  file: complaintModel
) => {
  // 准备查询
  const statement = `
    INSERT INTO resource
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, file);

  // 提供数据
  return data;
}

/**
 * 按 ID 查找文件
 */
export const findFileById = async (fileId: number, targetId: number, type: number) => {
  // 准备查询
  let sql = 'SELECT * FROM resource ';
  let and = false;
  if (fileId > 0) {
    sql += " where id = " + fileId;
    and = true;
  }
  if (targetId > 0) {
    sql += (and ? " and " : " where ") + " target_id = " + targetId;
    and = true;
  }
  if (type > 0) {
    sql += (and ? " and " : " where ") + " target_type = " + type;
  }

  // 执行查询
  const [data] = await connection.promise().query(sql);
  for (let item of data as any) {
    item.fullUrl = APP_URL + item.url + item.filename
  }
  // 提供数据
  return data as any;
}